<?php
/**
 * Created by PhpStorm.
 * User: chen
 * Date: 2015/12/31
 * Time: 13:29
 */
class CommAction extends Action{
    /**
     * 获取一个可用的token
     */
    public function getToken(){
        $platModel=D('wechat_plat');
        $authInfo=$platModel->find();
        $token=$authInfo['accessToken'];
        $tokenTime=$authInfo['accessTime'];
        $appId=$authInfo['appId'];
        $appSecret=$authInfo['appSecret'];
        if ($tokenTime < time()) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appId&secret=$appSecret";
            $res = json_decode($this->httpGet($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $tokenTime = time() + 7000;
                $token = $access_token;
                //把accesstoken写入数据表
                $authInfo['accessToken']=$token;
                $authInfo['accessTime']=$tokenTime;
                $platModel->data($authInfo)->save();
            }
        }
        return $token;
    }

    /**
     * 通过接口获取用户微信信息
     */
    public function getWxInfo($openid){
        $token=$this->getToken();
        $url="https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$token."&openid=".$openid."&lang=zh_CN";
        $result=$this->httpGet($url);
        $result=json_decode($result,true);
        $data=$result;
        $data['imgurl']=str_replace("http://wx.qlogo.cn/mmopen/","",$result['headimgurl']);
        return $data;
    }
    
    public function httpGet($url)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
}